#ifndef NET_TIMER_QUEUE_H_
#define NET_TIMER_QUEUE_H_

#include "base/base.h"
#include "net/poller.h"

namespace net {
struct Timer {
    explicit Timer(Closure* cb, bool is_repeat = false, int32 delay_sec = 0);

    int32 delay_;
    bool repeat_;
    struct timespec ts_;
    scoped_ptr<Closure> cb_;

    bool operator <(const Timer& rhs) const;
    bool operator <(const Timer* ts) const;
    bool operator <(const struct timespec* rhs) const;
    bool operator <(const struct timespec& ts) const;

    void AdjustTime();
};

class TimerQueue {
  public:
    typedef std::list<Timer*> TimerList;

    explicit TimerQueue(Poller* poller)
        : poller_(poller), timer_fd_(-1) {
      CHECK(CreateTimerFd());
      AddTimerEvent();
    }

    ~TimerQueue();

    void AddTimer(Timer* const timer);

    void CallActiveTimer(const struct timespec& ts);

    static void HandleReadEv(int fd, void* arg, int event);
  private:
    Poller* poller_;
    Event timer_ev_;int32 timer_fd_;

    TimerList timer_queue_;

    bool CreateTimerFd();
    void AddTimerEvent();

    void AdjustTriggerTime();

//    void CancleTimer(const Timer& t);
    DISALLOW_COPY_AND_ASSIGN(TimerQueue);
};
}

#endif
